from flask_restful import fields, Resource, marshal, marshal_with

# 返回值类型, @marshal_with装饰器模式，marshal普通模式

# fields String,Integer,Float, Boolean,DateTime,List,Nested
# attribute,default,required,readonly,format,validate,allow_null
user = {
    "1": {"username": "king", "password": "123456", "age": 18},
    "2": {"username": "king1", "password": "123456", "age": 19},
    "3": {"username": "king3", "password": "123456", "age": 20}
}

user_fields_list = {
    "1": {"username": "king", "password": "123456", "age": 18, "skill": ["游泳", "射击", "击剑"]},
    "2": {"username": "king1", "password": "123456", "age": 19, "skill": ["英语"]},
    "3": {"username": "king3", "password": "123456", "age": 20, "skill": ["数学", "物理"]}
}

resource_fields = {
    "username": fields.String,
    "password": fields.String,
    "age": fields.Integer
}

# 修改响应属性名
rename_resource_fields = {
    "name": fields.String(attribute="username"),  # 属性名username 改为name
    "password": fields.String,
    "age": fields.Integer
}

list_resource_fields = {
    "name": fields.String(attribute="username"),  # 属性名username 改为name
    "password": fields.String(),
    "age": fields.Integer(),
    "skill": fields.List(fields.String)  # 列表形式
}


# Nested 嵌套结构
class User:
    def __init__(self, id, username, books):
        self.id = id
        self.username = username
        self.books = books


class Books:
    def __init__(self, id, name, price):
        self.id = id
        self.name = name
        self.price = price


book_fileds = {
    "id": fields.String(),
    "name": fields.String(),
    "price": fields.String,
}

user_fields = {
    "username": fields.String,
    "password": fields.String,
    "books": fields.Nested(book_fileds)
}


class UserResourceNested(Resource):

    @marshal_with(user_fields)
    def get(self):
        book1 = Books(id=1, name="PHP", price="100")
        book2 = Books(id=2, name="PYTHON", price="1001")

        u = User(id=1, username="张三", books=[book1, book2])
        return u


class UserResource(Resource):
    @marshal_with(resource_fields)
    def get(self, id):
        print(id)
        print("###")
        return user[id]


class UserResource2(Resource):
    def get(self, id):
        return marshal(user[id], resource_fields, envelope="info")


class UserResourceRename(Resource):
    @marshal_with(rename_resource_fields, envelope="info")
    def get(self, id):
        return user[id]


class UserResourceFiledsList(Resource):

    @marshal_with(list_resource_fields)
    def get(self, id):
        return user_fields_list[id]
